window.addEventListener('DOMContentLoaded', function () {
    let myform = document.forms.myform;
    let elements = myform.elements;

    myform.addEventListener('submit', function (event) {
        // 阻止默认行为
        event.preventDefault();

        // 发送ajax请求 
        ajax({
            url: this.action,
            method: 'POST',
            data: `username=${elements.username.value}&password=${elements.password.value}`,
            success: function (data) {
                console.log(data);
                if (data === 'success') {
                    window.location.href = './index.html';
                }
            },
            error: function (err) {
                alert(err.msg);
            }
        })
    });
})

function ajax({ url, method, data, success, error }) {
    const xhr = new XMLHttpRequest();

    // 事件监听
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                // 我们需要对不同的业务逻辑返回状态做处理
                let res = JSON.parse(xhr.responseText); // {code: '200', msg: '', data: undefined}
                if (res.code === '200') {
                    success(res.data);
                } else {
                    error(res);
                }
            } else {
                // 展示错误信息
                console.log(xhr.statusText);
                alert(xhr.statusText);
            }
        }
    };

    xhr.open(method, url);

    // 设置请求头的信息，必须放在open方法调用后
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.send(data || null);
}

